<template>
  <div class="profile-view">
    <div class="profile-container">
      <h1 class="title">用户资料</h1>
      
      <div class="section">
        <h2 class="section-title">基本信息</h2>
        <div class="profile-info">
          <div class="info-row">
            <div class="info-label">用户名</div>
            <div class="info-value">{{ userProfile ? userProfile.username : '加载中...' }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">注册时间</div>
            <div class="info-value">{{ formatDate(userProfile ? userProfile.createdAt : null) }}</div>
          </div>
        </div>
      </div>
      
      <div class="section">
        <h2 class="section-title">修改密码</h2>
        <form @submit.prevent="changeUserPassword" class="change-password-form">
          <div class="form-group">
            <label for="current-password">当前密码</label>
            <input 
              type="password" 
              id="current-password" 
              v-model="passwordForm.oldPassword"
              placeholder="请输入当前密码" 
              required
            />
          </div>
          
          <div class="form-group">
            <label for="new-password">新密码</label>
            <input 
              type="password" 
              id="new-password" 
              v-model="passwordForm.newPassword"
              placeholder="请输入新密码（至少6位）" 
              required
              minlength="6"
            />
          </div>
          
          <div class="form-group">
            <label for="confirm-password">确认密码</label>
            <input 
              type="password" 
              id="confirm-password" 
              v-model="passwordForm.confirmPassword"
              placeholder="请再次输入新密码" 
              required
            />
          </div>
          
          <div v-if="passwordMessage" :class="['message', passwordMessage.success ? 'success' : 'error']">
            {{ passwordMessage.text }}
          </div>
          
          <div class="form-actions">
            <button 
              type="submit" 
              class="primary-button"
              :disabled="isChangingPassword"
            >
              {{ isChangingPassword ? '修改中...' : '修改密码' }}
            </button>
          </div>
        </form>
      </div>
      
      <div class="actions">
        <button @click="handleLogout" class="logout-button">退出登录</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getUserProfile, changePassword, logout } from '@/services/auth';

export default {
  name: 'ProfileView',
  setup() {
    const router = useRouter();
    const userProfile = ref(null);
    const isChangingPassword = ref(false);
    const passwordMessage = ref(null);
    
    const passwordForm = ref({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    });
    
    onMounted(() => {
      loadUserProfile();
    });
    
    // 加载用户资料
    const loadUserProfile = () => {
      const profile = getUserProfile();
      if (!profile) {
        // 未登录，重定向到登录页
        router.push('/login');
        return;
      }
      
      userProfile.value = profile;
    };
    
    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return '未知';
      
      try {
        const date = new Date(dateStr);
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        });
      } catch (e) {
        return dateStr;
      }
    };
    
    // 修改密码
    const changeUserPassword = () => {
      // 重置消息
      passwordMessage.value = null;
      
      // 验证表单
      if (!passwordForm.value.oldPassword || 
          !passwordForm.value.newPassword || 
          !passwordForm.value.confirmPassword) {
        passwordMessage.value = {
          success: false,
          text: '请填写所有密码字段'
        };
        return;
      }
      
      if (passwordForm.value.newPassword.length < 6) {
        passwordMessage.value = {
          success: false,
          text: '新密码至少需要6个字符'
        };
        return;
      }
      
      if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
        passwordMessage.value = {
          success: false,
          text: '两次输入的新密码不一致'
        };
        return;
      }
      
      isChangingPassword.value = true;
      
      try {
        const result = changePassword(
          passwordForm.value.oldPassword,
          passwordForm.value.newPassword
        );
        
        passwordMessage.value = {
          success: result.success,
          text: result.message
        };
        
        if (result.success) {
          // 清空表单
          passwordForm.value.oldPassword = '';
          passwordForm.value.newPassword = '';
          passwordForm.value.confirmPassword = '';
        }
      } catch (error) {
        console.error('修改密码出错:', error);
        passwordMessage.value = {
          success: false,
          text: '修改密码过程中出错'
        };
      } finally {
        isChangingPassword.value = false;
      }
    };
    
    // 退出登录
    const handleLogout = () => {
      logout();
      router.push('/login');
    };
    
    return {
      userProfile,
      passwordForm,
      passwordMessage,
      isChangingPassword,
      formatDate,
      changeUserPassword,
      handleLogout
    };
  }
}
</script>

<style scoped>
.profile-view {
  padding: 2rem;
  max-width: 800px;
  margin: 0 auto;
}

.profile-container {
  background-color: white;
  border-radius: 10px;
  padding: 2rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.title {
  font-size: 1.8rem;
  font-weight: 700;
  color: #333;
  margin-bottom: 2rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #eaeaea;
}

.section {
  margin-bottom: 2rem;
  padding-bottom: 2rem;
  border-bottom: 1px solid #eaeaea;
}

.section:last-child {
  border-bottom: none;
}

.section-title {
  font-size: 1.2rem;
  font-weight: 600;
  color: #555;
  margin-bottom: 1.5rem;
}

.profile-info {
  background-color: #f9fafb;
  border-radius: 6px;
  padding: 1.5rem;
}

.info-row {
  display: flex;
  margin-bottom: 1rem;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  flex: 0 0 100px;
  font-weight: 500;
  color: #666;
}

.info-value {
  flex: 1;
  color: #333;
}

.change-password-form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  max-width: 500px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

label {
  font-size: 0.9rem;
  font-weight: 500;
  color: #555;
}

input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 0.95rem;
  transition: border-color 0.2s;
}

input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(16, 163, 127, 0.2);
}

.message {
  padding: 0.75rem;
  border-radius: 6px;
  margin-top: 0.5rem;
}

.success {
  background-color: rgba(16, 163, 127, 0.1);
  color: var(--primary-color);
}

.error {
  background-color: rgba(239, 68, 68, 0.1);
  color: #ef4444;
}

.form-actions {
  margin-top: 1rem;
}

.primary-button {
  background-color: var(--primary-color);
  color: white;
  border: none;
  padding: 0.85rem 1.5rem;
  border-radius: 6px;
  font-weight: 500;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.2s;
}

.primary-button:hover {
  background-color: #0d926f;
}

.primary-button:disabled {
  background-color: #94d3c4;
  cursor: not-allowed;
}

.actions {
  display: flex;
  justify-content: center;
  margin-top: 1rem;
}

.logout-button {
  background-color: transparent;
  color: #ef4444;
  border: 1px solid #ef4444;
  padding: 0.75rem 1.5rem;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.logout-button:hover {
  background-color: rgba(239, 68, 68, 0.1);
}

@media (max-width: 768px) {
  .profile-view {
    padding: 1rem;
  }
  
  .profile-container {
    padding: 1.5rem;
  }
  
  .info-row {
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .info-label {
    flex: initial;
  }
}
</style> 